package org.zjx.manager;

import org.zjx.core.GameWindow;
import org.zjx.core.IWindow;
import org.zjx.util.HwndUtil;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 全局激活管理器 - 负责管理窗口激活权的分配和释放
 * 确保同一时间只有一个窗口处于激活状态
 */
public class ActivationManager {
    // 使用公平锁确保激活权按请求顺序分配
    private static final Lock activationLock = new ReentrantLock(true);

    // 条件变量用于等待激活权释放
    private static final Condition activationReleased = activationLock.newCondition();

    // 当前激活的窗口，volatile确保多线程可见性
    private static volatile GameWindow activeWindow = null;

    // 激活超时时间（毫秒）
    private static final long ACTIVATION_TIMEOUT = 30000;

    /**
     * 请求窗口激活权
     * @param requestingWindow 请求激活的窗口
     * @return true-获得激活权，false-获取失败（超时或中断）
     */
    public static boolean requestActivation(GameWindow requestingWindow) {
        // 首先检查是否已经是激活窗口（重入情况）
        if (activeWindow == requestingWindow) {
            return true;
        }

        activationLock.lock();
        try {
            long startTime = System.currentTimeMillis();

            // 等待直到激活权可用或超时
            while (activeWindow != null) {
                // 检查是否超时
                if (System.currentTimeMillis() - startTime > ACTIVATION_TIMEOUT) {
                    System.err.println("Window " + requestingWindow.getId() + " activation request timeout");
                    return false;
                }

                try {
                    // 等待激活权释放信号，每100毫秒检查一次
                    boolean signaled = activationReleased.await(100, java.util.concurrent.TimeUnit.MILLISECONDS);
                    if (activeWindow == null) {
                        break; // 激活权已释放，退出等待
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.err.println("Window " + requestingWindow.getId() + " activation request interrupted");
                    return false;
                }
            }

            // 获得激活权，设置当前激活窗口
            activeWindow = requestingWindow;

            // 修复：直接执行激活操作，而不是通过提交命令（避免递归）
            System.out.println("[Activation] Window " + requestingWindow.getId() + " activated successfully");
            HwndUtil.preposition(requestingWindow.getHwnd());

            return true;

        } finally {
            activationLock.unlock();
        }
    }

    /**
     * 释放窗口激活权
     * @param window 要释放激活权的窗口
     */
    public static void releaseActivation(IWindow window) {
        activationLock.lock();
        try {
            // 只有当前激活窗口才能释放激活权
            if (activeWindow == window) {
                activeWindow = null;
                System.out.println("[Activation] Window " + window.getId() + " released activation");
                // 通知所有等待激活权的窗口
                activationReleased.signalAll();
            }
        } finally {
            activationLock.unlock();
        }
    }

    /**
     * 检查指定窗口是否是当前激活窗口
     * @param window 要检查的窗口
     * @return true-是激活窗口，false-不是激活窗口
     */
    public static boolean isActiveWindow(IWindow window) {
        return activeWindow == window;
    }

    /**
     * 强制释放激活权（用于异常情况处理）
     */
    public static void forceReleaseActivation() {
        activationLock.lock();
        try {
            if (activeWindow != null) {
                System.out.println("[Activation] Force releasing activation from window " + activeWindow.getId());
                activeWindow = null;
                activationReleased.signalAll();
            }
        } finally {
            activationLock.unlock();
        }
    }
}